 /**
 * 简易版本的socketIo通讯组件
 * 使用方式参考使用说明
 * 部署时候package.json内的组件可能有点旧， 可以手动安装
 * @author 晓风<215628355@qq.com>
 */
//引入http模块
var socketio = require('socket.io'),
    http     = require('http'),
    domain   = require('domain'),  
	redis    = require('redis'),
    redisio  = require('socket.io-redis'),
    config   = require('./config.js');
	
var d = domain.create();
d.on("error", function(err) {
    console.log(err);
}); 

var sockets = {};
var chat_history={};
var chat_interval={};

var clientRedis  = redis.createClient(config['REDISPORT'],config['REDISHOST']);
if(config['REDISPASS']){
    clientRedis.auth(config['REDISPASS']);
}
console.log(config)
clientRedis.select(config['REDISSELECT']);//选择数据库序号
clientRedis.set("_service_redis_test",1);	


var server = http.createServer(function(req, res) {
    res.writeHead(200, {
        'Content-type': 'text/html;charset=utf-8'
    });
    res.end();
}).listen(config['port'], function() {
    console.log('服务开启',config['port']);
});

var io = socketio.listen(server,{
    pingTimeout: 60000,
    pingInterval: 25000
});

io.on('connection', function(socket) {
    console.log('连接成功');
    //进入房间
    socket.on('conn', function(data) {
        console.log('---消息内容---',data); 
        if(typeof data != 'object'){    
            return false;
        }  
        if(!data || !data.uid || !data.userSig){
            socket.emit('conn',['no']);  
            console.log('验证失败',data);   
			socket.disconnect();		
            return !1;
        }
		clientRedis.get('ST_'+data.userSig,function(error,res){
			if(error){
				console.log('error',error);
				socket.emit('conn',['no']);  
				socket.disconnect();	
				return;
			}
			if(res==null || res != data.uid){
				console.log('redis:',res);
				socket.emit('conn',['no']);  
				socket.disconnect();	
				return;
			}
            //账号互顶,若不设置互顶，PC客服端可能会发生错误
            old_socket = sockets[data.uid];
            if (old_socket && old_socket != socket) {
                //console.log("删除老的socket"+old_socket.id , old_socket);                
                old_socket.disconnect();
            }
			socket.uid  = data.uid;	
			socket.join(data.uid);
            sockets[socket.uid] = socket;
			  
			socket.emit('conn',['ok']);    	
			io.emit('login',{uid:data.uid});		
			console.log('握手成功',data);     
            //如有此值，表示是客服上线
            if(data.service){
                clientRedis.hset('service_user_list',socket.uid,socket.uid);  
            }else{
                clientRedis.hset('service_client_list',socket.uid,socket.uid);  
            }			
			clientRedis.del('ST_'+data.userSig);
		}) 		
        return;
    });
    //私聊   
    socket.on('sendmsg',function(data){
        if(typeof data != 'object'){          
            return false;
        }    	
		if(!socket.uid){
			return false;
		}
		process_msg(io,data.uid,data.msg); 	
    });
    //群发
    socket.on('sendall',function(data){
        console.log("群发",data);
        if(data.token == config['token']){
            io.emit('broadcastingListen',[data.msg]);
        }
    });    
    //资源释放
    socket.on('disconnect', function() {
        d.run(function() {
            if(socket.uid){	  
			    io.emit('loginout',{uid:socket.uid});
				console.log("退出",socket.uid);  
				socket.leave(socket.uid);     
			    clientRedis.hdel('service_user_list',socket.uid); 		
                clientRedis.hdel('service_client_list',socket.uid); 	
                sockets[socket.uid] = null;
				delete sockets[socket.uid];                
            }  
			delete io.sockets.sockets[socket.id]; 
        });
    });
});

function process_msg(io,roomnum,data){
    console.log("------process_msg: "+ roomnum +"------\r\n");
    console.log(data);
    if(!chat_history[roomnum]){
        chat_history[roomnum]=[];
    }
    chat_history[roomnum].push(data);
    chat_interval[roomnum] || (chat_interval[roomnum]=setInterval(function(){
        if(chat_history[roomnum].length>0){
            send_msg(io,roomnum);
        }else{
            clearInterval(chat_interval[roomnum]);
            chat_interval[roomnum]=null;
        }
    },200));
}

function send_msg(io,roomnum){
    var data=chat_history[roomnum].splice(0,chat_history[roomnum].length);
    io.sockets.in(roomnum).emit("broadcastingListen", data);
}